<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use Exception;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 线路站点管理
 *
 * @icon fa fa-circle-o
 */
class Linestation extends Backend
{

    /**
     * Line_station模型对象
     * @var \app\admin\model\Line_station
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Linestation;
        $this->view->assign("isShangList", $this->model->getIsShangList());
        $this->view->assign("isJieList", $this->model->getIsJieList());
        $this->view->assign("isXiaList", $this->model->getIsXiaList());
        $this->view->assign("isSongList", $this->model->getIsSongList());
        $this->view->assign("mapTypeList", $this->model->getMapTypeList());
    }


    public function index()
    {
        $this->assignconfig('ids', $this->request->param("ids"));
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $this->assign('line_id', $this->request->param("line_id"));
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if($params['is_shang']==1 && $params['is_xia']==1) exception('同一站点不能既是上车点又是下车点');
            if($params['is_shang']==0) $params['is_jie']=0;
            if($params['is_xia']==0) $params['is_song']=0;

            if($params['map_type'] == 2){
                $params['map_json'] = '[' .$params['map_json']. ']';
            }
            
            $station = db('station')->where('id',$params['station_id'])->field('area,station_name,coordinate_lat,coordinate_lng')->find();
            $params['area'] = $station['area'];
            $params['station_name'] = $station['station_name'];
            $params['coordinate_lat'] = $station['coordinate_lat'];
            $params['coordinate_lng'] = $station['coordinate_lng'];
            $result = $this->model->allowField(true)->save($params);

            $this->updateLine($params['line_id']);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    public function updateLine($line_id)
    {
        $line_data = db('line_station')->where(['line_id'=>$line_id])
            ->field('id,station_name,tags')->order('weigh desc')->select();
        $line_count = count($line_data);
        $begin = $line_data[0]['station_name'];
        $begin_tags = $line_data[0]['tags'];
        $end = $line_data[$line_count-1]['station_name'];
        $end_tags = $line_data[$line_count-1]['tags'];
        $cloum = array_column($line_data,'station_name');
        $way = join('、',$cloum);
        db('line')->where('id',$line_id)->update([
            'start_station' => $begin,
            'start_tags' => $begin_tags,
            'end_station' => $end,
            'end_tags' => $end_tags,
            'way' => $way
        ]);
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            if($params['is_shang']==1 && $params['is_xia']==1) exception('同一站点不能既是上车点又是下车点');
            if($params['is_shang']==0) $params['is_jie']=0;
            if($params['is_xia']==0) $params['is_song']=0;

            if($params['map_type'] == 2){
                $params['map_json'] = '[' .$params['map_json']. ']';
            }

            $station = db('station')->where('id',$params['station_id'])->field('area,station_name,coordinate_lat,coordinate_lng')->find();
            $params['area'] = $station['area'];
            $params['station_name'] = $station['station_name'];
            $params['coordinate_lat'] = $station['coordinate_lat'];
            $params['coordinate_lng'] = $station['coordinate_lng'];
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $line_id = $list[0]->line_id;

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            $this->updateLine($line_id);

            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

}
